package com.seeyon.apps.thirdapp.util;

import com.alibaba.fastjson.JSONObject;
import com.seeyon.apps.thirdapp.constants.Constants;
import com.seeyon.apps.thirdapp.domain.AccessToken;
import com.seeyon.apps.thirdapp.domain.MessageJSON;
import com.seeyon.ctp.util.LightWeightEncoder;
import com.seeyon.ctp.util.Strings;
import com.seeyon.ctp.util.json.JSONUtil;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

//import net.sf.json.JSONObject;

public class LanxinUtil {
	private static final Log      			log         = LogFactory.getLog(LanxinUtil.class);

	public static Map<String, AccessToken> accessTokens = new HashMap<String, AccessToken>();

	/**
	 * 调用接口获取TOKEN
	 * @return
	 */
	public static AccessToken getLxAppToken()
	{
		AccessToken accessToken = new AccessToken();
		JSONObject ret;
		log.info("客开【TOKEN】获取URL： " + Constants.LX_APPTOKEN_URL);
		if (Constants.LX_APPTOKEN_URL.contains("https")) {
			ret = HttpRequestUtil.httpsRequest(Constants.LX_APPTOKEN_URL,"GET",null);
		}else {
			ret = HttpRequestUtil.httpGet(Constants.LX_APPTOKEN_URL);

		}
		//JSONObject ret=HttpRequestUtil.httpsRequest(Constants.LX_APPTOKEN_URL,"GET",null);
		if (null == ret) {
			log.info("蓝信【token】获取app_token为空,连接为：" +  Constants.LX_APPTOKEN_URL);
			return null;
		}
		String appToken=null;
		log.info("客开【token】返回值： "+ret );
		if(ret.getIntValue("errCode") == 0)
		//if(ret.getInt("errCode")==0)
		{
			appToken=ret.getJSONObject("data").getString("appToken");
			accessToken.setToken(appToken);
			accessToken.setDate(new Date());
		}
		return accessToken;
	}


	public static AccessToken getLxAppTokenMsg()
	{
		AccessToken accessToken = new AccessToken();
		JSONObject ret;
		log.info("客开【TOKEN】获取URL： " + Constants.LX_APPTOKEN_URL_MSG);
		if (Constants.LX_APPTOKEN_URL_MSG.contains("https")) {
			ret = HttpRequestUtil.httpsRequest(Constants.LX_APPTOKEN_URL_MSG,"GET",null);
		}else {
			ret = HttpRequestUtil.httpGet(Constants.LX_APPTOKEN_URL_MSG);

		}
		//JSONObject ret=HttpRequestUtil.httpsRequest(Constants.LX_APPTOKEN_URL,"GET",null);
		if (null == ret) {
			log.info("蓝信【token】获取app_token为空,连接为：" +  Constants.LX_APPTOKEN_URL_MSG);
			return null;
		}
		String appToken=null;
		log.info("客开【token】返回值： "+ret );
		if(ret.getIntValue("errCode") == 0)
		//if(ret.getInt("errCode")==0)
		{
			appToken=ret.getJSONObject("data").getString("appToken");
			accessToken.setToken(appToken);
			accessToken.setDate(new Date());
		}
		return accessToken;
	}

	public static void main(String[] args) {
		String encoderUrl = LightWeightEncoder.decodeString("MHRmZnpwbzBJNjBkcG1tYmNwc2J1anBvMGpvZWZ5L2l1bm1AaXVubT4mM0d0ZmZ6cG8mM0duNCYzR2JxcXQmM0duNCYzR3VwZXAmM0dtYnpwdnUmM0d1cGVwLm1qdHUvaXVubQ%3D%3D");
		System.out.println("encoderUrl = " + encoderUrl);
	}

	/**
	 * 获取userToken
	 * @param appToken
	 * @param code
	 * @return
	 */
	public static String getLxUserToken(String appToken,String code)
	{
		String url= Constants.LX_USERTOKEN_URL.replace("@app_token@", appToken).replace("@code@", code);
		log.info("客开，【USERTOKEN】获取URL： " + url);
		JSONObject ret;
		if (url.contains("https")) {
			ret = HttpRequestUtil.httpsRequest(url,"GET",null);
		}else {
			ret = HttpRequestUtil.httpGet(url);

		}
		//JSONObject ret=HttpRequestUtil.httpsRequest(url,"GET",null);
		if (null == ret) {
			log.info("蓝信【USERTOKEN】获取user_token为空,连接为：" + url);
			return null;
		}
		String userToken=null;
		if(ret.getIntValue("errCode")==0)
		{
			userToken=ret.getJSONObject("data").getString("userToken");
		}else if(ret.getIntValue("errCode")== -3) {
			//apptoken 无效
			String app_token = getLxAccessToken(Constants.LX_APPID_FIRST,false).getToken();
			getLxUserToken(app_token, code);
		}
		log.info("客开，【USERTOKEN】获取返回值： " + JSONUtil.toJSONString(ret));
		return userToken;

	}
	/**
	 * 获取userInfo
	 * @param appToken
	 * @param userToken
	 * @param //id_value
	 * @return
	 */
	public static String getLxUserInfo(String appToken,String userToken)
	{
		String url= Constants.LX_USERINFO_URL.replace("@app_token@", appToken).replace("@user_token@", userToken);
		log.info("客开，【USERINFO】获取URL： " + url);
		JSONObject ret;
		if (url.contains("https")) {
			ret = HttpRequestUtil.httpsRequest(url,"GET",null);
		}else {
			ret = HttpRequestUtil.httpGet(url);

		}
		//JSONObject ret=HttpRequestUtil.httpsRequest(url,"GET",null);
		if (null == ret) {
			log.info("蓝信【USERINFO】获取user_info为空,连接为：" + url);
			return null;
		}
		String tel=null;
		if(ret.getIntValue("errCode")==0)
		{
			tel=ret.getJSONObject("data").getJSONObject("mobilePhone").getString("number");
		}else if(ret.getIntValue("errCode")== -3) {
			String app_token = getLxAccessToken("OATOKEN", false).getToken();
			getLxUserInfo(app_token, userToken);
		}
		log.info("客开，【USERINFO】获取返回值： " + JSONUtil.toJSONString(ret));
		return tel;
	}


	/**
	 * 获取Receiver
	 * @param appToken
	 * @param  //userToken
	 * @param // mobile
	 * @return
	 */
	public static String getLxReceiver(String appToken,String idValue)
	{
		String url= Constants.LX_MSSMEMBER_URL.replace("@app_token@", appToken).replace("@id_value@", idValue);
		log.info("客开，【LxReceiver】获取URL： " + url);
		JSONObject ret;
		if (url.contains("https")) {
			ret = HttpRequestUtil.httpsRequest(url,"GET",null);
		}else {
			ret = HttpRequestUtil.httpGet(url);

		}
		//JSONObject ret=HttpRequestUtil.httpsRequest(url,"GET",null);
		if (null == ret) {
			log.info("蓝信【LXReceiver】获取Receiver为空,连接为：" + url);
			return null;
		}
		String Receiver=null;
		if(ret.getIntValue("errCode")==0)
		{
			Receiver=ret.getJSONObject("data").getString("staffId");
		}else{
			log.info("蓝信【LXReceiver】获取Receiver为空,连接为：" + url);
		}
		log.info("客开，【LxReceiver】获取返回值： " + JSONUtil.toJSONString(ret));
		return Receiver;
	}


	/**
	 * 蓝信发送消息处理
	 * @param apptoken
	 * @param msg
	 * @return
	 */
	public static String sendLxMessage(String apptoken, MessageJSON msg) {

		String mssageUrl = Constants.LX_MSSAGE_URL.replace("@app_token@", apptoken);

		//将信息内容转化为蓝信所需的json格式
		log.info("蓝信发送【oa_card_msg】请求地址：" + mssageUrl );
		log.info("蓝信发送【oa_card_msg】请求参数："+JSONUtil.toJSONString(msg));
		long startInterTime = System.currentTimeMillis();

		JSONObject jsonbject = HttpRequestUtil.sendPost(mssageUrl, JSONUtil.toJSONString(msg));

		long endInterTime = System.currentTimeMillis();
		log.info("蓝信【oa_card_msg】 调用发送消息接口执行共计花费时间： " +(endInterTime - startInterTime) + " ms");
		log.info("蓝信发送【oa_caed_msg】返回参数：" +JSONUtil.toJSONString(jsonbject));
		if (jsonbject.getIntValue("errCode")==0) {
			log.info("蓝信发送【oa_card_msg】消息发送成功: " + jsonbject.get("errMsg"));
			return null;
		}else if(jsonbject.getIntValue("errCode")== -3) {
			//apptoken 无效
			String app_token = getLxAccessToken("MSGTOKEN", false,true).getToken();
			sendLxMessage(app_token, msg);
		}
		log.info("蓝信发送【oa_card_msg】发送失败，失败详情： " + jsonbject.get("errMsg"));
		return null;
	}


	/**
	 * 根据APPID获取TOKEN
	 * @param appid
	 * @param flag
	 * @return
	 */
	public static AccessToken getLxAccessToken(String appid, boolean flag) {
		long newDate = 0;
		long oldDate = 300000;
		String token = null;
		// 应用access_token已经存在
		if(accessTokens.get(appid) != null) {
			token = accessTokens.get(appid).getToken();
			newDate = new Date().getTime();
			oldDate = accessTokens.get(appid).getDate().getTime();
		}
		// token已经存在并且没有过期则直接返回token 有效期2小时
		if(Strings.isNotBlank(token) && newDate - oldDate < 1000*60*60*2 && flag) {
			return accessTokens.get(appid);
		} else {
			AccessToken accessToken = new AccessToken();
			accessToken= getLxAppToken();
			if (accessToken.getToken() == null || "".equals(accessToken.getToken())) {
				log.info("客开，【TOKEN】TOKEN获取失败，清查原因！");
				accessToken = null;
				return null;
			}
			accessTokens.put(appid, accessToken);
			return accessToken;
		}
	}

	/**
	 * 重写 消息和应用不是一个appid了
	 * @param appid
	 * @param flag
	 * @return
	 */
	public static AccessToken getLxAccessToken(String appid, boolean flag,boolean isMsg) {
		long newDate = 0;
		long oldDate = 300000;
		String token = null;
		// 应用access_token已经存在
		if(accessTokens.get(appid) != null) {
			token = accessTokens.get(appid).getToken();
			newDate = new Date().getTime();
			oldDate = accessTokens.get(appid).getDate().getTime();
		}
		// token已经存在并且没有过期则直接返回token 有效期2小时
		if(Strings.isNotBlank(token) && newDate - oldDate < 1000*60*60*2 && flag) {
			return accessTokens.get(appid);
		} else {
			AccessToken accessToken = new AccessToken();
			accessToken= getLxAppTokenMsg();
			if (accessToken.getToken() == null || "".equals(accessToken.getToken())) {
				log.info("客开，【TOKEN】TOKEN获取失败，清查原因！");
				accessToken = null;
				return null;
			}
			accessTokens.put(appid, accessToken);
			return accessToken;
		}
	}



	public static String getOaUser(String tel)
	{
		//JSONObject tokenObject = null;
		String tokenUrl= Constants.OA_TOKEN_URL;
		JSONObject ret = null;
		/*if (tokenUrl.contains("https")) {
			tokenObject = HttpRequestUtil.httpsRequest(tokenUrl,"GET",null);
  		}else {
  			tokenObject = HttpRequestUtil.httpGet(tokenUrl);

  		}*/
		//String token = HttpRequestUtiltoken.getTokenString(tokenUrl);
		String object = httpGet(tokenUrl);
		log.info("客开，【getOaUser】access获取tokenobj:"+ object);
		JSONObject tokenInfo = JSONUtil.parseJSONString(object, JSONObject.class);
		String token = tokenInfo.getString("id");
		if(token==null){
			log.info("客开，【getOaUser】 request url 返回NULL");
		}else{
			log.info("客开，【getOaUser】获取token:"+token);
			String url= Constants.OA_LOGINNAME_URL.replace("@telephone@", tel).replace("@token@", token);
			log.info("客开,【OaUser】获取登录名 url"+url);
			if (url.contains("https")) {
				ret= HttpRequestUtil.httpsRequest(url,"GET",null);

				if (null == ret) {
					log.info("客开,【OaUser】获取登录名为空,连接为：" + url);
					return null;
				}
			}else {
				ret= HttpRequestUtil.httpGet(url);
				if (null == ret) {
					log.info("客开,【OaUser】获取登录名为空,连接为：" + url);
					return null;
				}

			}
		}
		log.info("客开，【OaUser】loginName： " + ret.getString("loginName"));
		return ret.getString("loginName");
	}

	private static String httpGet(String url) {
		// get请求返回结果
		String jsonResult = null;
		try {
			DefaultHttpClient client = new DefaultHttpClient();
			// 发送get请求
			HttpGet request = new HttpGet(url);
			request.addHeader("Accept", "application/json");

			HttpResponse response = client.execute(request);

			/** 请求发送成功，并得到响应 **/
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				/** 读取服务器返回过来的json字符串数据 **/
				String strResult = EntityUtils.toString(response.getEntity());
				// System.out.println(strResult);
				/** 把json字符串转换成json对象 **/
//	  	    jsonResult = JSONObject.fromObject(strResult);
				jsonResult = strResult;
				url = URLDecoder.decode(url, "UTF-8");
			} else {
				// logger.error("get请求提交失败:" + url);
			}
			client.close();
		} catch (IOException e) {
			// logger.error("get请求提交失败:" + url, e);
		}

		return jsonResult;
	}







}
